﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using TidyBlog.Util;
using TidyBlog.MVC;
using TidyBlog.Entity;
using TidyBlog.BLL;
using TidyBlog.MVC.WWW.Models;

namespace TidyBlog.MVC.WWW.Controllers
{
    /// <summary>
    /// 用户管理控制器 /Manage_User/{action}
    /// </summary>
    public class Manage_UserController : ManageController
    {
        /// <summary>
        /// 用户列表（搜索）
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="groupid">用户组编号</param>
        /// <param name="nickname">昵称</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ActionResult List(string username, int? groupid, string nickname, int? page)
        {
            var urlParams = new Dictionary<string, string>();
            urlParams.Add("username", username);
            urlParams.Add("groupid", groupid.GetValueOrDefault().ToString());
            urlParams.Add("nickname", nickname);
            
            var result = UserBLL.List(urlParams, 20, page.GetValueOrDefault());

            var paginatorHref = new StringBuilder(Request.Path);
            paginatorHref.Append("?");
            if (urlParams.Count > 0)
            {
                foreach (var param in urlParams)
                {
                    paginatorHref.Append(param.Key);
                    paginatorHref.Append("=");
                    paginatorHref.Append(param.Value);
                    paginatorHref.Append("&");
                }
            }
            paginatorHref.Append("page={0}");

            return View(new ListWithPaginator<User>()
            {
                SearchParams = urlParams,
                Result = result,
                ResultPaginator = new Paginator(result.CurrentPage, result.PageCount, paginatorHref.ToString())
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            // TODO 检查管理员级别

            UserBLL.Delete(id);

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "已删除指定用户",
                Link = Request.UrlReferrer.ToString()
            });

            return new EmptyResult();
        }

        /// <summary>
        /// 创建用户界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(User user)
        {
            UserBLL.Create(user);

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "已添加用户 " + user.UserName,
                Link = Url.Action("Create"),
                LinkText = "继续添加"
            });

            return new EmptyResult();
        }

        /// <summary>
        /// 编辑用户界面
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var user = UserBLL.Read(id);
            if (user == null)
            {
                throw new Exception("用户不存在");
            }

            return View(user);
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(User user)
        {
            var oldUser = UserBLL.Read(user.UserId);
            if (oldUser == null)
            {
                throw new Exception("用户不存在");
            }

            // 密码为空时，不更新密码（使用旧密码）
            if (String.IsNullOrEmpty(user.Password))
            {
                user.Password = oldUser.Password;
            }

            UserBLL.Update(user);

            RespondentInfo.Success(this.ControllerContext, new OperInfo()
            {
                Message = "更新完成"
            });

            return new EmptyResult();
        }
    }
}
